<?php
namespace Modules\Admin\Http\Controllers;
use Illuminate\Http\Request;
class EnvController extends CommonController
{
    private $env;
    public function __construct()
    {
        $this->env = base_path() . '/.env';
        parent::__construct();
    }
    /**
     * @name  列表
     */
    public function index()
    {
        return view('admin::env.index');
    }
    /**
     * @name  列表数据
     */
    public function data(Request $request)
    {
        $data = $this->getEnv();
        return response()->json(['code' => 0, 'msg'   => config('admin.limit_msg'),'data'=>$data,'rel'=>1]);
    }
    /**
     * @name  编辑页面
     */
    public function edit($id)
    {
        $info = $this->getEnv($id);
        return view('admin::env.edit',compact('info'));
    }
    /**
     * @name  编辑数据处理
     */
    public function update(Request $request,$id)
    {
        $data = $request->all();
        if($this->setEnv($data['key'],$data['value'])){
            return response()->json([
                'status'=>1,
                'error' => '',
                'msg' => config('admin.update_success'),
                'url'=>route('admin.env.index')
            ],200);
        }else{
            return response()->json([
                'status'=>0,
                'error' => config('admin.update_error'),
                'msg' => '',
                'url'=>route('admin.env.index')
            ],201);
        }
    }
    /**
     * @name  获取env数据
     */
    private function getEnv($id = null)
    {
        $string = file_get_contents($this->env);
        $string = preg_split('/\n+/', $string);
        $array = [];
        foreach ($string as $k => $one) {
            if (preg_match('/^(#\s)/', $one) === 1 || preg_match('/^([\\n\\r]+)/', $one)) {
                continue;
            }
            $entry = explode("=", $one, 2);
            if (!empty($entry[0])) {
                $array[] = ['id' => $k + 1, 'key' => $entry[0], 'value' => isset($entry[1]) ? $entry[1] : null];
            }
        }
        if (empty($id)) {
            return $array;
        }
        $index = array_search($id, array_column($array, 'id'));
        return $array[$index];
    }
    /**
     * @name  更新数据
     */
    private function setEnv($key, $value)
    {
        $array = $this->getEnv();
        $index = array_search($key, array_column($array, 'key'));
        if ($index !== false) {
            $array[$index]['value'] = $value; // 更新
        } else {
            array_push($array, ['key' => $key, 'value' => $value]); // 新增
        }
        return $this->saveEnv($array);
    }
    /**
     * @name  写入env文件
     */
    private function saveEnv($array)
    {
        if (is_array($array)) {
            $newArray = [];
            $i = 0;
            foreach ($array as $env) {
                if (preg_match('/\s/', $env['value']) > 0 && (strpos($env['value'], '"') > 0 && strpos($env['value'], '"', -0) > 0)) {
                    $env['value'] = '"'.$env['value'].'"';
                }
                $newArray[$i] = $env['key']."=".$env['value'];
                $i++;
            }
            $newArray = implode("\n", $newArray);
            file_put_contents($this->env, $newArray);
            return true;
        }
        return false;
    }

}